package com.liuzh.kaoyanspringboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuzh.kaoyanspringboot.common.Result;
import com.liuzh.kaoyanspringboot.entity.Subject;
import com.liuzh.kaoyanspringboot.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘志鸿
 * @since 2023-03-08
 */
@RestController
@RequestMapping("/subject")
public class SubjectController {

    @Autowired
    private SubjectService subjectService;

    // 新增或更新
    @PostMapping
    public Result save(@RequestBody Subject subject) {
        return Result.success(subjectService.saveOrUpdate(subject));
    }

    // 根据 id 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(subjectService.removeById(id));
    }

    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(subjectService.removeBatchByIds(ids));
    }

    //查询所有数据
    @GetMapping
    public Result findAll() {
        return Result.success(subjectService.list());
    }

    // 根据 id 查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(subjectService.getById(id));
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param name
     * @param code
     * @return
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String code) {
        IPage<Subject> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
        if(!"".equals(code)){
            queryWrapper.like("code",code);
        }
//        System.out.println(subjectService.page(page, queryWrapper));
        return Result.success(subjectService.page(page, queryWrapper));
    }


    /**
     * 导出接口
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查出所有的数据
        List<Subject> list = subjectService.list();
        //通过工具类创建writer写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUpLoadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("name","名称");
        writer.addHeaderAlias("code","专业代码");

        //一次性写出list内的对象到Excel, 使用默认样式，强制输出标题
        writer.write(list, true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.speadsheetml.sheet;charset-utf-8");
        String fileName = URLEncoder.encode("考研专业信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        // 通过 response.getOutputStream() 获取输出流， 把writer刷新到out输出流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * Excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream =file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        /**
         * 正统做法
         * 不用指定
         * @Alias("昵称")
         * private String nickname;
         * 也可以使用
         */
        reader.addHeaderAlias("名称","name");
        reader.addHeaderAlias("专业代码","code");
        List<Subject> list = reader.readAll(Subject.class); //指定类型
//        System.out.println(list);
        return Result.success(subjectService.saveBatch(list));
    }

}

